package com.servlet;

import com.dao.TypeDao;
import com.entity.*;
import com.entity.Type;
import com.service.FoodsService;
import com.service.TypeService;
import com.service.UserService;
import com.service.impl.FoodsServiceImpl;
import com.service.impl.TypeServiceImpl;
import com.service.impl.UserServiceImpl;
import com.util.DateHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/foods.let")
public class FoodServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2.获取各种对象
        PrintWriter out = resp.getWriter();
        String type = req.getParameter("type");
        FoodsService foodsService=new FoodsServiceImpl();
        TypeService  typeService= new TypeServiceImpl();
        UserService userService=new UserServiceImpl();
        switch (type){
            case "findall":
                List<Foods> foods=foodsService.foodsFindAll();
                List<Like> likes=foodsService.findLike();
                List<Like> loves=foodsService.findUserLove();
                session.setAttribute("likes",likes);
                session.setAttribute("loves",loves);
                req.getRequestDispatcher("menu.jsp").forward(req,resp);
                break;
            case "menuList":
                int pageSize=8;
                int pageIndex = Integer.parseInt( req.getParameter("pageIndex"));
                int pageCount = foodsService.getPageCount(pageSize);
                if(pageIndex<1){
                    pageIndex=1;
                }
                if(pageIndex>pageCount){
                    pageIndex=pageCount;
                }
                List<Foods> foodsList = foodsService.foodList(pageIndex,pageSize);
                req.setAttribute("foodsList",foodsList);
                req.setAttribute("pageCount",pageCount);
                req.getRequestDispatcher("menu-list.jsp?pageIndex="+pageIndex).forward(req,resp);
                break;
            case "lovethree":
                List<Map<String, Object>> lovethree = foodsService.findThree();
                List<Like> love = foodsService.findUserLove();
                List<Like> like = foodsService.findLike();
//                List<Like> lovess = foodsService.findUserLove();
                List<Type> typeList = typeService.getAll();
                List<Map<String, Object>> foodes = foodsService.foodFindAll();
                session.setAttribute("lovethree", lovethree);
                session.setAttribute("love", love);
                session.setAttribute("likes", like);
//                session.setAttribute("loves", lovess);
//                session.setAttribute("typeList",typeList);
                session.setAttribute("foods",foodes);
                if (session.getAttribute("user") == null){
                    User user=new User();
                    user.setId(-1);
                    session.setAttribute("user",user);
                    req.getRequestDispatcher("home-1.jsp").forward(req, resp);
                }else{

                    req.getRequestDispatcher("home-1.jsp").forward(req, resp);
                }
                break;
            case "foodGiveLike":
                if (session.getAttribute("user") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='home-1.jsp';</script>");
                    return;
                }
                int customerId = Integer.parseInt(req.getParameter("customerId"));
                int foodId = Integer.parseInt(req.getParameter("foodId"));
                int num = foodsService.findFoodLike(customerId, foodId);
                if (num != 0) {
                    foodsService.foodCancelLike(customerId, foodId);
                    out.write("no");
                } else {
                    foodsService.foodGiveLike(customerId, foodId);
                    out.write("yes");
                }
                break;
            case "findId":
                if (session.getAttribute("user") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='home-1.jsp';</script>");
                    return;
                }
                int foodsId = Integer.parseInt(req.getParameter("foodId"));
                int typeId = Integer.parseInt(req.getParameter("typeId"));
                pageIndex=Integer.parseInt(req.getParameter("pageIndex"));
                List<Map<String, Object>> food = foodsService.findId(foodsId);
                List<Map<String, Object>> likenumber = foodsService.likeId(foodsId);
                List<Map<String, Object>> liketype = foodsService.typeId(typeId);
                List<Like> lovesss = foodsService.findUserLove();
                List<Like> likees = foodsService.findLike();
                req.setAttribute("loves", lovesss);
                req.setAttribute("food", food);
                req.setAttribute("likenumber", likenumber);
                req.setAttribute("liketype",liketype);
                req.setAttribute("likes",likees);
                req.getRequestDispatcher("/comment.let?type=queryAllComment&foodId="+foodsId+"&typeId="+typeId+"&pageIndex="+pageIndex).forward(req,resp);
                break;
            case "cart":
                String fall=null;
                int size =Integer.parseInt(req.getParameter("size"));
                if (size==0){
                    fall="小份";
                }else if (size==4){
                    fall="中份";
                }else if (size==8){
                    fall="大份";
                }
                int number =Integer.parseInt(req.getParameter("number"));
                int userId =Integer.parseInt(req.getParameter("userId"));
                int fId =Integer.parseInt(req.getParameter("foodId"));
                int price =Integer.parseInt(req.getParameter("price"));
                List<Map<String, Object>> sum=foodsService.listCart(price,number,userId,fId,size);
                if (sum==null){
                    int list=foodsService.updataCart(price,number,userId,fId,size,fall);
                }
                List<Cart> listCart = foodsService.findCart(userId);
                req.setAttribute("listCart",listCart);
                out.println("<script>location.href='/foods.let?type=findCart&userId="+userId+"';</script>");
                break;
            case "findCart":
                userId =Integer.parseInt(req.getParameter("userId"));
                int cartNum=userService.getCartNum(userId);
                session.setAttribute("cartNum",cartNum);
                listCart = foodsService.findCart(userId);
                req.setAttribute("listCart",listCart);
                req.getRequestDispatcher("cart.jsp").forward(req,resp);
                break;
            case "updataCart":
                int numbers =Integer.parseInt(req.getParameter("number"));
                int listCartId =Integer.parseInt(req.getParameter("listCartId"));
                int list=foodsService.updetaNumber(listCartId,numbers);
                req.getRequestDispatcher("cart.jsp").forward(req,resp);
                break;
            case "remove":
//                userId =Integer.parseInt(req.getParameter("userId"));
                int listCartid =Integer.parseInt(req.getParameter("listCartId"));
                int remove=foodsService.removeCart(listCartid);
                break;
            case "bgFindAll":
                pageSize=12;
                pageIndex = Integer.parseInt( req.getParameter("pageIndex"));
                pageCount = foodsService.getPageCount(pageSize);
                if(pageIndex<1){
                    pageIndex=1;
                }
                if(pageIndex>pageCount){
                    pageIndex=pageCount;
                }
                List<Map<String, Object>> bgFoods=foodsService.bgFoodsFindAll(pageIndex,pageSize);
                req.setAttribute("bgFoods",bgFoods);
                req.setAttribute("page",pageCount);
                req.getRequestDispatcher("/bgFoodKa/detail/foodList.jsp?pageIndex="+pageIndex).forward(req,resp);
                break;
            case "removeFood":
                int id1 = Integer.parseInt(req.getParameter("foodId"));
                int i = foodsService.deleteFood(id1);
                if(i>0){
                    out.println("<script>alert('食物删除成功'); location.href='/foods.let?type=bgFindAll&pageIndex=1';</script>");
                }else{
                    out.println("<script>alert('食物删除失败'); location.href='/foods.let?type=bgFindAll&pageIndex=1';</script>");
                }
                break;
            case "modifypre":
                foodId = Integer.parseInt(req.getParameter("foodId"));
                System.out.println(foodId);
                List<Map<String, Object>> bgFoodByID=foodsService.bgFoodGetByID(foodId);
                List<Type> foodType=typeService.getAll();
                System.out.println(bgFoodByID);
                System.out.println(foodType);
                req.setAttribute("foodTypes",foodType);
                req.setAttribute("bgFood",bgFoodByID);
                req.getRequestDispatcher("/bgFoodKa/detail/updateFood.jsp").forward(req,resp);
                break;
            case "modifyFood":
                try {
                    modify(req,resp,out);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "addFood":
                try {
                    add(req,resp,out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "queryFoodByName":
                String foodName=req.getParameter("foodName");
                System.out.println(foodName);
                List<Map<String, Object>> bgFoodByName=foodsService.bgFoodGetByName(foodName);
                System.out.println(bgFoodByName);
                if (bgFoodByName!=null){
                    req.setAttribute("bgFoods",bgFoodByName);
                    req.getRequestDispatcher("/bgFoodKa/detail/foodList.jsp").forward(req,resp);
                }
                break;
            case "findOrder":
                userId = Integer.parseInt(req.getParameter("userId"));
                List<Map<String,Object>> order=foodsService.getOrderByUserId(userId);
                if (order==null){
                    out.println("<script>alert('您当前未存在订单');top.location.replace('/PersonalCenter/main.jsp');</script>");
                }else {
                    System.out.println(order);
                    req.setAttribute("order",order);
                    req.getRequestDispatcher("/PersonalCenter/orderManagement.jsp").forward(req,resp);
                }
                break;
            case "addOrder":
                userId = Integer.parseInt(req.getParameter("userId"));
                int addOrder = foodsService.addOrder(userId);
                Orders orders = foodsService.orderById(userId);
                if(addOrder!=0){
                    out.println("<script> location.href='/Order.let?type=listOrderById&userId="+userId+"';</script>");
                }else {
                    out.println("<script>alert('失败'); location.href='home-1.jsp';</script>");
                }
                break;
    }
        out.flush();
        out.close();

    }

    private void add(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置大小
        factory.setSizeThreshold(1024 * 9);
        //临时存放仓库
        File file = new File("C:\\temp");
        //判断有没有这个文件夹，没有则创建一个个
        if (!file.exists()) {
            file.mkdir();
        }
        factory.setRepository(file);
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //将请求解析
        List<FileItem> fileItems = fileUpload.parseRequest(req);
//遍例取出表单元素和图片上传
        Foods foods = new Foods();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString("utf-8");
                switch (name) {
                    case "cid":
                        foods.setType_id(Integer.parseInt(value));
                        break;
                    case "foodName":
                        foods.setName(value);
                        break;
                    case "price":
                        foods.setPrice(Integer.parseInt(value));
                        break;
                    case "describe":
                        foods.setDescribe(value);
                        break;
                }
            } else {
                String fileName = item.getName();
                //获取后缀
                String filterName = fileName.substring(fileName.lastIndexOf("."));
                //修改文件名
                fileName = DateHelper.getImageName() + filterName;
                //实际路径·
                String path = req.getServletContext().getRealPath("/assets/img/product");
                String filePath = path + "/" + fileName;
                String dbPath = "/assets/img/product/" + fileName;
                foods.setPhoto(dbPath);
                item.write(new File(filePath));
            }
        }
        //将信息保存在数据库
        FoodsService foodsService=new FoodsServiceImpl();
        int count = foodsService.add(foods.getName(), foods.getPhoto(),foods.getPrice(),foods.getDescribe(),foods.getType_id());
        if(count>0){
            out.println("<script>alert('食物添加成功');location.href= '/foods.let?type=bgFindAll&pageIndex=1';</script>");
        }else {
            out.println("<script>alert('食物添加失败');location.href= '/bgFoodKa/detail/saveFood.jsp';</script>");
        }
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置大小
        factory.setSizeThreshold(1024*9);
        //临时存放仓库
        File file = new File("C:\\temp");
        //判断有没有这个文件夹，没有则创建一个个
        if (!file.exists()){
            file.mkdir();
        }
        factory.setRepository(file);
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //将请求解析
        List<FileItem>fileItems = fileUpload.parseRequest(req);
        Foods foods = new Foods();
        for(FileItem item:fileItems){
            if(item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString("utf-8");
                switch (name){
                    case "cid":
                        foods.setType_id(Integer.parseInt(value));
                        break;
                    case "id":
                        foods.setId(Integer.parseInt(value));
                        break;
                    case "foodName":
                        foods.setName(value);
                        break;
                    case "price":
                        foods.setPrice(Integer.parseInt(value));
                        break;
                    case "pic":
                        foods.setPhoto(value);
                        break;
                    case "describe":
                        foods.setDescribe(value);
                        break;
                }
            }else {
                String fileName = item.getName();
                if (fileName.trim().length() > 0) {
                    //获取后缀
                    String filterName = fileName.substring(fileName.lastIndexOf("."));
                    //修改文件名
                    fileName = DateHelper.getImageName() + filterName;
                    //实际路径·
                    String path = req.getServletContext().getRealPath("/assets/img/product");
                    String filePath = path + "/" + fileName;
                    String dbPath = "/assets/img/product/" + fileName;
                    foods.setPhoto(dbPath);
                    item.write(new File(filePath));
                }
            }
        }
        //将信息保存在数据库
        FoodsService foodsService=new FoodsServiceImpl();
        int count = foodsService.modify(foods);
        if(count>0){
            out.println("<script>alert('食物修改成功');location.href= '/foods.let?type=bgFindAll&pageIndex=1';</script>");
        }else {
            out.println("<script>alert('食物修改失败');location.href= '/foods.let?type=bgFindAll&pageIndex=1';</script>");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


}
